<template>
  <div class="qr-code-card">
    <div class="card-info">
      <p><strong>Name:</strong> {{ name }}</p>
      <p><strong>Organization:</strong> {{ org }}</p>
      <p><strong>Phone (Mobile):</strong> {{ mobile }}</p>
      <p><strong>Phone (Work):</strong> {{ workPhone }}</p>
    </div>
    <canvas ref="qrCanvas"></canvas>
    <button @click="downloadQrCode">Download QR Code</button>
    <button @click="uploadQrCode">Upload QR Code</button>
  </div>
</template>

<script>
import QRCode from 'qrcode'
import axios from 'axios'

export default {
  name: 'QrCodeCard',
  props: {
    name: {
      type: String,
      default: '赵 姝'
    },
    org: {
      type: String,
      default: '昆山开发区党工委委员  管委会副主任'
    },
    mobile: {
      type: String,
      default: '138 1289 6855'
    },
    workPhone: {
      type: String,
      default: '86-512-57352515'
    }
  },
  mounted() {
    this.generateQRCode()
  },
  methods: {
    generateQRCode() {
      // 使用VCARD格式的名片信息
      const vCardInfo = `BEGIN:VCARD\nVERSION:3.0\nN:${this.name}\nORG:${this.org}\nTEL;pager;VOICE:${this.mobile}\nTEL;WORK;VOICE:${this.workPhone}\nEND:VCARD`
      const canvas = this.$refs.qrCanvas
      QRCode.toCanvas(canvas, vCardInfo, { width: 200 }, (error) => {
        if (error) console.error(error)
      })
    },
    downloadQrCode() {
      const canvas = this.$refs.qrCanvas
      const link = document.createElement('a')
      link.href = canvas.toDataURL('image/png') // 获取二维码的Base64图片
      link.download = 'qrcode.png' // 设置下载的文件名
      link.click() // 触发下载
    },
    async uploadQrCode() {
      const canvas = this.$refs.qrCanvas
      canvas.toBlob(async (blob) => {
        const formData = new FormData()
        formData.append('file', blob, 'qrcode.png') // 将图片 Blob 添加到表单数据中

        try {
          const response = await axios.post('/api/upload', formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          })
          console.log('Upload success:', response.data)
        } catch (error) {
          console.error('Upload failed:', error)
        }
      })
    }
  }
}
</script>

<style scoped>
.qr-code-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20px;
}

.card-info {
  margin-bottom: 10px;
  text-align: center;
}

button {
  margin-top: 10px;
}
</style>
